﻿using System;
using System.Linq;
using System.Security.AccessControl;
using Microsoft.Win32;

namespace regsecedit
{
	class Program
	{
		static void Main(params string[] args)
		{
			if (args.Length == 0
				|| args.Contains(Factory.HelpFlag))
			{
				Console.WriteLine(Resources.Help);
				return;
			}

			if (args.Contains(Factory.FormFlag))
			{
				CommanLineBuilder form = new CommanLineBuilder();
				form.ShowDialog();
				return;
			}

			Console.WriteLine(Resources.NotifyStartMessage);

			Factory factory = new Factory();
			ExecutionInfo executionInfo = factory.CreateExecutationInfo();
			// TODO: validate parameters

			try
			{
				RegistryKey registryKey = ConvertBranchToRegistry(executionInfo.MainBranch);

				registryKey = registryKey.OpenSubKey(executionInfo.PathToKey, true);

				RegistryAccessRule registryAccessRule = new RegistryAccessRule(
					executionInfo.User,
					executionInfo.Permission,
					executionInfo.InheritanceFlags,
					executionInfo.PropagationFlags,
					executionInfo.AccessControlType);

				RegistrySecurity registrySecurity = new RegistrySecurity();
				registrySecurity.SetAccessRule(registryAccessRule);
				registryKey.SetAccessControl(registrySecurity);

				Console.WriteLine(Resources.SuccessMessage);

			}
			catch (Exception ex)
			{
				Console.WriteLine("ERROR: {0}", ex.ToString());
			}
		}

		private static T StrToEnum<T>(string s)
		{
			return (T)Enum.ToObject(typeof(T), int.Parse(s));
		}

		public static RegistryKey ConvertBranchToRegistry(Branch branch)
		{
			switch (branch)
			{
				case Branch.ClassesRoot:
					return Registry.ClassesRoot;
				case Branch.CurrentConfig:
					return Registry.CurrentConfig;
				case Branch.CurrentUser:
					return Registry.CurrentUser;
				case Branch.DynData:
					return Registry.DynData;
				case Branch.LocalMachine:
					return Registry.LocalMachine;
				case Branch.PerformanceData:
					return Registry.PerformanceData;
				case Branch.Users:
					return Registry.Users;
				default:
					throw new Exception();
			}
		}
	}
}

